package com.gimi.cloud.jimi.client.service.product.impl;

import java.io.UnsupportedEncodingException;
import java.util.*;

import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.commonService.service.CoreSecurityInstructionsService;
import com.gimi.cloud.jimi.dto.product.ProductDto;
import com.gimi.cloud.jimi.dto.product.ProductSkuDto;
import com.gimi.cloud.jimi.dto.product.ProductSkuImgDTO;
import com.gimi.cloud.jimi.dto.product.SecurityInstructionsDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gimi.cloud.jimi.client.service.product.ProductService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.dao.dao.prod.ProdCatModelDao;
import com.gimi.cloud.jimi.dao.dao.prod.ProdCatModelValueDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductImgDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductSkuDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductSkuImgDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductStatusDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductValueAddDao;
import com.gimi.cloud.jimi.entity.prod.ProdCatModelEntity;
import com.gimi.cloud.jimi.entity.product.ProductEntity;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class ProductServiceImpl implements ProductService {
    private static Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);
    @Autowired
    private ProductDao productDao;
    @Autowired
    private ProductStatusDao productStatusDao;
    @Autowired
    private ProductImgDao productImgDao;
    @Autowired
    private ProductSkuDao productSkuDao;
    @Autowired
    private ProductSkuImgDao productSkuImgDao;
    @Autowired
    private ProductValueAddDao productValueAddDao;
    @Autowired
    private ProdCatModelValueDao prodCatModelValueDao;
    @Autowired
    private ProdCatModelDao prodCatModelDao;
    @Autowired
    private CoreSecurityInstructionsService coreSecurityInstructionsService;

    /**
     * 查询商品详情信息
     */
    @Override
    public ProductDto getProductDetail(ProductDto productDto) throws Exception {
        String prodId = productDto.getProdId();
        if (prodId != null) {
            ProductDto dto = productDao.findByProdId(prodId);
            dto.setAdImg(AliOSSUtil.getFileUrl(dto.getAdImg(), AliOSSUtil.getNoEffictDateByDay(1)));
            List<String> list = productImgDao.selectUrlByprodId(prodId);
            List<String> aliUrlList = new ArrayList<>();
            if (list != null && list.size() > 0) {
                for (String url : list) {
                    aliUrlList.add(AliOSSUtil.getFileUrl(url, AliOSSUtil.getNoEffictDateByDay(1)));
                }
            }
            dto.setProductImgUrl(aliUrlList);
            //查询商品增值服务
            dto.setProductValueAddEntity(productValueAddDao.selectByPrimaryKey(prodId));
            //查询出所有的商品说明保障
            List<SecurityInstructionsDTO> securityInstructionsDTOS = coreSecurityInstructionsService.getAllBySort();
            dto.setSecurityInstructionsDto(securityInstructionsDTOS);
            return dto;
        } else {
            throw new MsgException(ResponseCodeEnum.FAILURE, "商品id不能为空!");
        }
    }

    /**
     * 商品规格属性列表(所有)
     */
    @Override
    public List<Map<String, Object>> getProductProp(ProductDto productDto) throws Exception {
        ProductEntity entity = productDao.selectByPrimaryKey(productDto.getProdId());
        List<ProdCatModelEntity> list = prodCatModelDao.findCatModelByCatId(entity.getProdCatId());//颜色/内存

        List<Map<String, Object>> propList = new ArrayList<>();

        for (ProdCatModelEntity prodCatModel : list) {
            Map<String, Object> map = new HashMap<>();
            List<String> modleValueList = prodCatModelValueDao.selectModelValueByModelId(prodCatModel.getModelId());
            //map.put(prodCatModel.getProdPropName(), modleValueList);
            map.put("model", prodCatModel.getProdPropName());
			map.put("modelValue", modleValueList);
            propList.add(map);
        }
        return propList;
    }

    /**
     * sku有库存的属性列表
     */
    @Override
    public List<ProductSkuDto> getModelValueList(ProductDto productDto) throws Exception {
    	List<ProductSkuDto> skuDtoList = productSkuDao.selectByProdIdAndStock(productDto.getProdId());// (25,26),(25,21)

		for (ProductSkuDto productSkuDto : skuDtoList) {
			List<Map<String, Object>> modelValueList = prodCatModelValueDao.getModelIdByIds(productSkuDto.getSkuValue());
			// 查询每条有库存的sku对应的规格
			if (modelValueList != null && modelValueList.size() > 0) {
				List<Object> list2 = new ArrayList<>();
				for (Map<String, Object> map : modelValueList) {
					Map mapValue = new HashMap<>();
					//mapValue.put(map.get("skuDetailKey"), map.get("skuDetailValue"));// [{"内存":"1g"},{"颜色":"土豪金"}]
					mapValue.put("model", map.get("skuDetailKey"));
					mapValue.put("modelValue", map.get("skuDetailValue"));
					list2.add(mapValue);
				}
				productSkuDto.setSkuValue(JsonUtil.toJson(list2));
			}
			// 单品图片
			List<String> skuImgList = productSkuImgDao.getSkuImgsByProdId(productSkuDto.getSkuId());
			List<String> aliUrlList = new ArrayList<>();
			if (skuImgList != null && skuImgList.size() > 0) {
				for (String url : skuImgList) {
					aliUrlList.add(AliOSSUtil.getFileUrl(url, AliOSSUtil.getNoEffictDateByDay(1)));
				}
				productSkuDto.setProdSkuImgs(aliUrlList);
			} else {
				productSkuDto.setProdSkuImgs(new ArrayList<>());
			}
		}
		logger.info("该商品有库存的sku组合列表为==>" + JsonUtil.toJson(skuDtoList));
		return skuDtoList;
    }


    /**
     * 查询商品详情信息
     * 此接口一下返回商品全部详细信息,因前端不好解析,拆分成上面的三个接口,此接口暂时没用到.
     */
    @Override
    public ProductDto getProductDetails(ProductDto productDto) throws Exception {
        //验证是否是当前店铺,商品状态
        String prodId = productDto.getProdId();
        int num = productStatusDao.getProdStatus(prodId);
        if (num != 1) {
            throw new MsgException(ResponseCodeEnum.PROD_STATUS_ERR, "商品状态错误!");
        }
        ProductDto dto = productDao.selectByProdId(prodId);
        if (dto != null) {
            try {
                dto.setSpecParameter(new String(dto.getSpecParameters(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                logger.info("商品规格参数转UTF-8失败");
                return null;
            }
            try {
                String catId = dto.getProdCatId();
                dto.setFirstCatId(catId.substring(0, 2));
                dto.setSecondCatId(catId.substring(0, 5));
            } catch (Exception e) {
                logger.error(e.getMessage());
                throw new MsgException(ResponseCodeEnum.PROD_PARAMS_ERR, "商品分类参数异常!");
            }
            dto.setProductValueAddEntity(productValueAddDao.selectByPrimaryKey(prodId));
            dto.setProductImgEntity(productImgDao.selectByprodId(prodId));
            List<ProductSkuDto> skuDto = productSkuDao.selectByProdId(prodId);
            if (skuDto != null && skuDto.size() > 0) {
                for (ProductSkuDto skus : skuDto) {
                    List<ProductSkuImgDTO> list = productSkuImgDao.selectBySkuId(skus.getSkuId());
                    if (list != null && list.size() > 0) {
                        skus.setProductSkuImgEntity(list);
                    } else {
                        skus.setProductSkuImgEntity(new ArrayList<>());
                    }
                    //skus.setSkuValueDetail(modelValueDao.getModelIdByIds(skus.getSkuValue()));
                    List<Map<String, Object>> skuList = prodCatModelValueDao.getModelIdByIds(skus.getSkuValue());
                    skus.setSkuValueDetail(skuList);
                }
            }
            dto.setProductSkuDto(skuDto);
        }
        return dto;
    }


}
